package com.xywl.escort.view.main;

import android.annotation.SuppressLint;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.view.ViewCompat;
import android.support.v4.view.WindowInsetsCompat;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.ashokvarma.bottomnavigation.BottomNavigationBar;
import com.ashokvarma.bottomnavigation.BottomNavigationItem;
import com.ashokvarma.bottomnavigation.TextBadgeItem;
import com.xywl.escort.R;
import com.xywl.escort.base.BaseActivity;
import com.xywl.escort.bean.MessageEvent;
import com.xywl.escort.utils.ToastUtil;
import com.xywl.escort.view.farm.FarmFragment;
import com.xywl.escort.view.home.HomeFragment;
import com.xywl.escort.view.market.MarketFragment;
import com.xywl.escort.view.tips.TipsFragment;
import com.xywl.escort.view.treasure.TreasureFragment;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.List;

import javax.inject.Inject;

import dagger.android.AndroidInjection;
import dagger.android.AndroidInjector;
import dagger.android.DispatchingAndroidInjector;
import dagger.android.support.HasSupportFragmentInjector;
import timber.log.Timber;

import static com.xywl.escort.common.Constant.EventType.EVENT_MAIN_TYPE;

@Route(path = "/xy/main")
public class MainActivity extends BaseActivity implements HasSupportFragmentInjector, BottomNavigationBar.OnTabSelectedListener {

    private BottomNavigationBar bottomNavigationBar;
    private TextBadgeItem badgeItem;

    private HomeFragment mHomeFragment;
    private FarmFragment mFarmFragment;
    private MarketFragment marketFragment;
    private TreasureFragment mTreasureFragment;
    private TipsFragment mTipsFragment;
    private FragmentManager fm;

    private long mExitTime;

    @Inject
    DispatchingAndroidInjector<Fragment> supportFragmentInjector;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        AndroidInjection.inject(this);
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        fm = getSupportFragmentManager();
        initBottomNavigationBar();

        setDefaultFragment();

        View view = findViewById(R.id.root_container_layout);
        if (null != view) {
            if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                ViewCompat.setOnApplyWindowInsetsListener(view, new android.support.v4.view.OnApplyWindowInsetsListener() {
                    @Override
                    public WindowInsetsCompat onApplyWindowInsets(View v, WindowInsetsCompat insets) {
                        return insets.consumeSystemWindowInsets();
                    }
                });
            }
        }
        EventBus.getDefault().register(this);
    }

    @Override
    public AndroidInjector<Fragment> supportFragmentInjector() {
        return supportFragmentInjector;
    }

    /**
     * 设置默认的
     */
    private void setDefaultFragment() {
        if (mHomeFragment == null) {
            mHomeFragment = HomeFragment.newInstance(getString(R.string.tab_home));
        }
        showFragment(mHomeFragment);
    }

    private void initBottomNavigationBar() {
        badgeItem = new TextBadgeItem().setBackgroundColorResource(R.color.colorPrimary).setText(String.valueOf(20));
        bottomNavigationBar = findViewById(R.id.bottomNavigationBar);
        bottomNavigationBar.clearAll();

        bottomNavigationBar.setMode(BottomNavigationBar.MODE_FIXED);
        bottomNavigationBar.setBackgroundStyle(BottomNavigationBar.BACKGROUND_STYLE_STATIC);

        bottomNavigationBar
                .addItem(new BottomNavigationItem(R.mipmap.home_nav_home, getString(R.string.tab_home)).setActiveColorResource(R.color.main_body_major_color)
                        .setInActiveColorResource(R.color.main_body_prompt_color).setInactiveIconResource(R.mipmap.home_nav_home_click))
                .addItem(new BottomNavigationItem(R.mipmap.home_nav_farm, getString(R.string.tab_farm)).setActiveColorResource(R.color.main_body_major_color)
                        .setInActiveColorResource(R.color.main_body_prompt_color).setInactiveIconResource(R.mipmap.home_nav_farm_click))
                .addItem(new BottomNavigationItem(R.mipmap.home_nav_bazaar, getString(R.string.tab_market)).setActiveColorResource(R.color.main_body_major_color)
                        .setInActiveColorResource(R.color.main_body_prompt_color).setInactiveIconResource(R.mipmap.home_nav_bazaar_click))
                .addItem(new BottomNavigationItem(R.mipmap.home_nav_treasure, getString(R.string.tab_treasure)).setActiveColorResource(R.color.main_body_major_color)
                        .setInActiveColorResource(R.color.main_body_prompt_color)
//                        .setBadgeItem(badgeItem)
                        .setInactiveIconResource(R.mipmap.home_nav_treasure_click))
                .addItem(new BottomNavigationItem(R.mipmap.home_nav_kits, getString(R.string.tab_tips)).setActiveColorResource(R.color.main_body_major_color)
                        .setInActiveColorResource(R.color.main_body_prompt_color).setInactiveIconResource(R.mipmap.home_nav_kits_click))
                .setFirstSelectedPosition(0)
                .initialise();

        bottomNavigationBar.setTabSelectedListener(this);
    }

    @Override
    public void onTabSelected(int position) {
        switch (position) {
            case 0:
                if (mHomeFragment == null) {
                    mHomeFragment = HomeFragment.newInstance(getString(R.string.tab_home));
                }
                showFragment(mHomeFragment);
                break;
            case 1:
                if (mFarmFragment == null) {
                    mFarmFragment = FarmFragment.newInstance(getString(R.string.tab_farm));
                }
                showFragment(mFarmFragment);
                break;
            case 2:
                if (marketFragment == null) {
                    marketFragment = MarketFragment.newInstance(getString(R.string.tab_market));
                }
                showFragment(marketFragment);
                break;
            case 3:
                if (mTreasureFragment == null) {
                    mTreasureFragment = TreasureFragment.newInstance(getString(R.string.tab_treasure));
                }
                showFragment(mTreasureFragment);
                break;
            case 4:
                if (mTipsFragment == null) {
                    mTipsFragment = TipsFragment.newInstance(getString(R.string.tab_tips));
                }
                showFragment(mTipsFragment);
                break;
            default:
                break;
        }
        // 事务提交
//        transaction.commit();
    }

    private void showFragment(Fragment fragment) {
        if (!fragment.isVisible()) {
            @SuppressLint("RestrictedApi") List<Fragment> fragList = fm.getFragments();
            FragmentTransaction transaction = fm.beginTransaction();
            if (fragList != null && fragList.contains(fragment)) {
                for (Fragment frag : fragList) {
                    if (frag.equals(fragment) && frag.isHidden()) {
                        transaction.show(frag);
                    } else {
                        transaction.hide(frag);
                    }
                }
                transaction.commitAllowingStateLoss();
            } else {
                if (fragList != null && fragList.size() > 0) {
                    for (Fragment frag : fragList) {
                        transaction.hide(frag);
                    }
                }
                transaction.add(R.id.bottom_nav_content, fragment);
                transaction.commitAllowingStateLoss();
            }
        }
    }

    @Override
    public void onTabUnselected(int position) {
    }

    @Override
    public void onTabReselected(int position) {
    }

    private void updateNum(int num) {
        if (num <= 0) {
            badgeItem.hide();
        } else {
            badgeItem.show();
            String numStr = num + "";
            if (num > 99) {
                numStr = "99+";
            }
            badgeItem.setText(numStr);
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void mainEventBus(MessageEvent event) {
        Timber.tag("MainActivity").e("event.message=" + event.message);
        Timber.tag("MainActivity").e("event.type=" + event.type);
        switch (event.type) {
            case EVENT_MAIN_TYPE:
                String message = event.message;
                if (!TextUtils.isEmpty(message)) {
                    if (message.equals("farm")) {
                        if (null != bottomNavigationBar) {
                            bottomNavigationBar.selectTab(1);
                        }
                    } else if (message.equals("market")) {
                        if (null != bottomNavigationBar) {
                            bottomNavigationBar.selectTab(2);
                        }
                    }
                }
                break;
            default:
                break;
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN) {
            if ((System.currentTimeMillis() - mExitTime) > 2000) {
                ToastUtil.showTip(this, R.string.app_exit_prompt);
                mExitTime = System.currentTimeMillis();
                return true;
            } else {
                finish();
            }
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }
}
